import { ref, reactive, toRefs, type Ref } from 'vue'
import { defineStore } from 'pinia'

export const useAudioStore = defineStore('audio', () => {
  // 响应式状态
  const state = reactive({
    filePath: '',
    isPlaying: false,
    stop: true,
    stopPlaybackOnEnd: true,
  })

  // 非响应式状态（不需要响应式的变量）
  let innerAudioContext: UniApp.InnerAudioContext | null = null

  // 方法实现
  const initAudioManager = () => {
    console.log('🎵 初始化背景音频管理器')

    // 创建并保存上下文
    innerAudioContext = uni.createInnerAudioContext()

    innerAudioContext.onPlay(() => {
      console.log('▶️ 音频开始播放')
      state.isPlaying = true
    })

    innerAudioContext.onPause(() => {
      console.log('⏸️ 音频已暂停')
      state.isPlaying = false
    })

    innerAudioContext.onStop(() => {
      console.log('⏹️ 音频已停止')
      state.isPlaying = false
    })

    innerAudioContext.onEnded(() => {
      console.log('✅ 当前段落播放完成，销毁组件')
      state.isPlaying = false

      if (state.stopPlaybackOnEnd) {
        console.log('销毁组件')
        destroyInnerAudioContext()
      } else {
        console.log('传播自动播放下一首事件')
        uni.$emit('autoPlayNext')
      }
    })

    innerAudioContext.onError((res) => {
      console.error('❌ 音频播放错误:', res.errMsg)
      stopPlayback()
    })
  }

  const togglePlayPause = async () => {
    if (state.isPlaying) {
      console.log('⏸ 用户点击暂停')
      pausePlayback()
    } else {
      console.log('▶ 用户点击播放')
      startPlayback()
    }
  }

  const startPlayback = () => {
    console.log('🚀 开始播放')
    state.stop = false
    playAudio()
  }

  const playAudio = () => {
    if (state.stop) return

    if (!innerAudioContext) {
      initAudioManager()
    }
    if (!innerAudioContext) return

    innerAudioContext.autoplay = true
    innerAudioContext.src = state.filePath
    innerAudioContext.play()
  }

  const pausePlayback = () => {
    console.log('⏸ 执行暂停')
    innerAudioContext?.pause()
  }

  const destroyInnerAudioContext = () => {
    if (innerAudioContext) {
      innerAudioContext.stop()
      innerAudioContext.destroy()
      innerAudioContext = null
    }
  }

  const stopPlayback = () => {
    console.log('⏹ 执行停止')
    destroyInnerAudioContext()
    state.isPlaying = false
    state.stop = true
  }

  // 暴露需要响应的状态和所有方法
  return {
    ...toRefs(state), // 转为 refs 以保持响应性
    togglePlayPause,
    startPlayback,
    pausePlayback,
    playAudio,
    stopPlayback,
    initAudioManager,
  }
})
